<template>
  <el-card class="list-page">
    <div class="list-h">
      <div>
        <el-button
          type="primary"
          @click="handleOperate('add')"
          v-auth="`/${menuType}/section--add`"
          class="add-option"
          >创建新合同</el-button
        >
        <el-button
          type="primary"
          @click="exportFunc"
          v-auth="`/${menuType}/section--export`"
          class="add-option"
          >导出</el-button
        >
      </div>

      <el-form
        :inline="true"
        :model="formInline"
        ref="formRef"
        class="demo-form-inline"
      >
        <el-form-item label="合同名称" prop="sectionNameLike">
          <el-input
            class="width-custom120"
            v-model="formInline.sectionNameLike"
            @change="handleSearch"
            clearable
          />
        </el-form-item>
        <el-form-item label="合同类型" prop="sectionType">
          <el-select
            v-model="formInline.sectionType"
            placeholder="请选择"
            class="width-custom120"
            @change="handleSearch"
            clearable
          >
            <el-option
              class="default-option"
              v-for="item in sectionTypeList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button
            type="primary"
            @click="handleSearch"
            v-auth="`/${menuType}/section--query`"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <el-skeleton
      style="height: calc(100vh - 300px)"
      :rows="8"
      :loading="loading"
      animated
    >
    </el-skeleton>
    <el-table
      :data="tableData"
      stripe
      v-loading="loading"
      v-show="!loading"
      :height="'calc(100vh - 300px)'"
      :header-cell-style="{
        background: '#F7F9FD',
        color: '#000',
        height: '48px',
        borderTop: '1px soild #E4E8F2'
      }"
    >
      <template #empty>
        <el-empty :image-size="150" description="暂无数据"></el-empty>
      </template>
      <el-table-column type="index" label="序号" width="50">
        <template v-slot="scope">
          <span>{{
            (formInline.pageNum - 1) * formInline.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="sectionCode" label="合同编号" width="240">
      </el-table-column>
      <el-table-column label="合同名称" width="240">
        <template #default="{ row }">
          <el-tooltip
            class="box-item"
            placement="bottom-end"
            popper-class="tooltip-popper"
          >
            <template #content>
              <div style="max-width: 260px; line-height: 18px">
                {{ row.sectionName }}
              </div>
            </template>
            <el-button
              type="text"
              class="shot-text"
              @click="lookMonomer(row)"
              >{{ row.sectionName }}</el-button
            >
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="合同类型" width="150">
        <template #default="{ row }">
          <span>{{ sectionTypeObj[row.sectionType] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="money"
        width="260"
        :align="'center'"
        label="合同金额"
      >
        <el-table-column
          prop="contractAmount"
          width="130"
          label="含税（元）"
        ></el-table-column>
        <el-table-column
          prop="currencyAmountNoTax"
          width="130"
          label="不含税（元）"
        ></el-table-column>
      </el-table-column>
      <el-table-column
        prop="projectNatureName"
        label="项目实施进度"
        width="200"
      >
        <template #default="{ row }">
          <el-select
            v-model="row.contractProgressCode"
            value-key="dicCode"
            class="width-custom180"
            @change="updateRow(row)"
          >
            <el-option
              class="default-option"
              v-for="item in progressList"
              :label="item.dicValue"
              :key="item.dicCode"
              :value="item.dicCode"
            ></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="createUserName" label="创建人"></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
      ></el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button
            type="text"
            @click="handleOperate('edit', row)"
            v-auth="`/${menuType}/section--edit`"
            >编辑</el-button
          >
          <el-button
            v-if="!['1', '2'].includes(row.startWorkStatus)"
            type="text"
            class="btns-danger"
            v-auth="`/${menuType}/section--delete`"
            @click="showDeleteMessageBox(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <re-pagination
      :total="total"
      v-show="total > 0"
      v-model:page="formInline.pageNum"
      v-model:limit="formInline.pageSize"
      @pagination="handleSearch(formInline.pageNum)"
    />
    <add-section
      v-if="addForm.isShow"
      :addForm="addForm"
      @cancelClose="addForm.isShow = false"
      @updateClose="updateClose"
    ></add-section>
  </el-card>
</template>

<script lang="ts">
import { reactive, toRefs, ref, defineComponent, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessageBox } from "element-plus";
import RePagination from "/@/components/RePagination/index.vue";
import NotifMessage from "/@/utils/message/notification";
import { getSection, deleSection, updateProcess } from "/@/api/projects";
import { storageLocal } from "/@/utils/storage";
import { clickEvent } from "/@/utils/func";
import { postDictList } from "/@/api/home";
import { exportExcel } from "/@/utils/file";
export default defineComponent({
  name: "section",
  components: {
    RePagination
  },
  props: {
    menuType: {
      type: String,
      default: "projectsA"
    }
  },

  setup(props) {
    let router = useRouter();
    const formRef = ref<HTMLFormElement | null>(null) as any;
    let loading = ref<boolean>(false);
    let total = ref<number>(0);
    let projectInfo = storageLocal.getItem("projectInfo");
    let formInline = reactive({
      projectId: projectInfo?.id,
      pageNum: 1,
      pageSize: 10,
      sectionNameLike: "",
      sectionType: ""
    });
    let sectionTypeList = ref([]);
    let sectionTypeObj = ref({});

    let state = reactive({
      tableData: []
    });
    let addForm = reactive({
      isShow: false,
      title: "创建新标段",
      type: "add",
      sectionId: ""
    });

    onMounted(() => {
      getSelectData();
    });
    // 重置条件
    const handleReset = (): void => {
      formRef.value.resetFields();
      getTableData(formInline);
    };

    // 根据条件进行搜索
    const handleSearch = (page?: any) => {
      if (!page) {
        formInline.pageNum = 1;
      }
      getTableData(formInline);
    };

    const updateRow = async row => {
      const { data } = await updateProcess({
        id: row.id,
        contractProgressCode: row.contractProgressCode,
        contractProgressName: progressList.value.find(
          item => item.dicCode === row.contractProgressCode
        ).dicValue
      });
      if (data) {
        NotifMessage.success("修改成功");
      }
    };

    // 获取实施进度
    const progressList = ref([]);
    const getSelectData = async () => {
      try {
        const { data } = await postDictList({
          dicType: "contract_progress_type"
        });
        progressList.value = data;
      } catch (error) {
        console.log(error);
      }
    };

    //获取单体列表
    const getTableData = async (obj: object = {}) => {
      loading.value = true;
      try {
        const { code, data } = await getSection(obj);
        if (code === 200) {
          state.tableData = data.list;
          total.value = data.rows;
        }
      } catch (err) {
        console.log(err);
      } finally {
        loading.value = false;
      }
    };

    const handleOperate = (type, row: any = {}) => {
      // if (type === "add") {
      //   addForm.title = "创建新标段";
      //   addForm.sectionId = ""
      // } else if (type === "edit") {
      //   addForm.title = "编辑标段";
      //   addForm.sectionId = row.id
      // }
      // addForm.type = type;
      // addForm.isShow = true;

      router.push({
        path: `/${props.menuType}/proManage/section/detail`,
        query: {
          id: row.id
        }
      });
    };

    // 删除单体
    const handleDelete = async (item: any) => {
      try {
        const { code, message } = await deleSection({ id: item.id });
        if (code === 200) {
          clickEvent("项目标段", "删除", "删除项目标段");
          NotifMessage.success(message);
          getTableData(formInline);
        } else {
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };
    const showDeleteMessageBox = row => {
      ElMessageBox.confirm("确定删除该条记录吗？", "", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        iconClass: "el-icon-warning"
      })
        .then(() => {
          handleDelete(row);
        })
        .catch(() => {});
    };

    const lookMonomer = row => {
      storageLocal.setItem("sectionInfo", {
        id: row.id,
        name: row.sectionName,
        leaderId: row.leaderId,
        leaderName: row.leaderName,
        sectionType: row.sectionType,
        startWorkId: row.startWorkId,
        startWorkStatus: row.startWorkStatus,
        sectionName: row.sectionName,
        sectionCode: row.sectionCode
      });
      // let nextProjectsS = router
      //   .getRoutes()
      //   .find(item => item.path === "/projectsS");
      // if (nextProjectsS) {
      //   router.removeRoute(nextProjectsS.name);
      // }
      if (row.sectionType == 4) {
        router.push({ path: "/projectsS/document/engineering" });
      } else {
        router.push({ path: "/projectsS" });
      }
    };

    const updateClose = async () => {
      getTableData(formInline);
      addForm.isShow = false;
    };

    // 合同类型
    const initSectionTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_sec_con_type" });
        sectionTypeList.value = data || [];
        sectionTypeList.value.forEach(item => {
          sectionTypeObj.value[item.dicCode] = item.dicValue;
        });
      } catch (err) {
        console.log(err);
      }
    };

    const exportFunc = async () => {
      let formData = {
        ...formInline,
        pageNum: 1,
        pageSize: 0
      };
      exportExcel(
        "/snow-admin/projectSection/export",
        formData,
        `${projectInfo?.name}_项目合同`
      );
    };

    // 请求数据
    initSectionTypeList();
    getTableData(formInline);
    return {
      ...toRefs(state),
      addForm,
      total,
      formRef,
      loading,
      formInline,
      sectionTypeList,
      sectionTypeObj,
      handleReset,
      handleSearch,
      handleDelete,
      showDeleteMessageBox,
      handleOperate,
      lookMonomer,
      updateClose,
      exportFunc,
      progressList,
      updateRow
    };
  }
});
</script>
<style>
.el-icon-warning {
  color: #e45d5d !important;
}
</style>
<style lang="scss" scoped>
.shot-text {
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  -webkit-line-clamp: 1;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  white-space: nowrap;
}
</style>
